import StorageUtils from './storage-utils';


interface ICacheRouteParams {
  currentLocation: {
    pathname: string;
    search: string;
    state?: Record<string, unknown>;
  };
  nextRoute: {
    pathname: string;
    search: string;
    state?: Record<string, unknown>;
  };
  targetRouteList: string[];
  cacheData: Record<string, unknown> | string;
}

// 缓存路由数据
export const CacheRouteParams = (options: ICacheRouteParams) => {
  const { currentLocation, nextRoute, targetRouteList, cacheData } = options;
  let needCache = false;
  //  判断是否需要缓存路由数据
  for (let index = 0; index < targetRouteList.length; index++) {
    const item = targetRouteList[index];
    if (nextRoute.pathname.indexOf(item) > -1) {
      needCache = true;
      break;
    }
  }
  if (needCache && cacheData) {
    SetRouteCache(currentLocation?.pathname, cacheData);
  }
};

export const SetRouteCache = (cacheKey, cacheData) => {
  StorageUtils.setItem(`${cacheKey}_route_cache`, JSON.stringify(cacheData), true);
};

export const RemoveRouteCache = (cacheKey) => {
  StorageUtils.removeItem(`${cacheKey}_route_cache`, true);
};

export const GetRouteCache = (cacheKey, _default = {}) => {
  const cache = StorageUtils.getItem(`${cacheKey}_route_cache`, null, true);
  StorageUtils.removeItem(`${cacheKey}_route_cache`, true);
  return cache ? JSON.parse(cache) : _default;
};